<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>费用科目</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
	<link rel="stylesheet" media="all" href="${pageContext.request.contextPath }/assets/formSelects/formSelects-v4.css">
</head>
<body class="layui-anim layui-anim-up">
    <div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>对账单</cite>
        </a>
      </span>
    </div>
    <div class="x-body">
      <div style="margin-bottom: 18px">
		<div class="layui-inline layui-form">
			<table>
				<tr>
					<td>
						<input class="layui-input" id="keyword01" placeholder="请输入对账单号" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					</td>
					<td>
						<div class="layui-input-block" style="width:180px;margin-left: 10px;">
							<select class="layui-input" id="keyword02" lay-search>
								<option value="">请选择供应商</option>
								<c:forEach items="${customers}" var="customer">
									<option value="${customer.id}">${customer.customer_name}</option>
								</c:forEach>  
							</select>
						</div>
					</td>
					<td class="layui-input-inline">
						<input class="layui-input" id="startTime1" placeholder="请输入开始时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						-<input class="layui-input" id="endTime1" placeholder="请输入结束时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px"> 
					</td>
					<td>
						<div class="layui-input-block" style="width:180px;margin-left: 10px;">
							<select class="layui-input" id="keyword03" lay-search>
								<option value="">请选择单据状态</option>
								<option value="0">否</option>
								<option value="1">是</option>
							</select>
						</div>
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon">&#xe615;</i>检索</button>
	  </div>
      <xblock>
			<button id="add" class="layui-btn layui-btn-warm"><i class="layui-icon"></i>新增</button>
			<button id="dels" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
			<button id="reconciliation" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-ok"></i>对账</button>
			<button id="printing" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-print"></i>打印</button>
      </xblock> 
	  <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
	  <div id="detailsDiv" hidden="hidden">
		  <table class="layui-hide" id="tableListDetails" lay-filter="tableListDetails"></table>
	  </div>
	</div>
	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
	</script>

	<div id="addDivID" hidden="hidden">
		<form class="layui-form" id="addFormID">
			<xblock>
				<table>
					<tr>
						<td>
							<label class="layui-form-label">对账单号</label></td>
						<td>
							<input class="layui-input" id="oddNumbers" name="oddNumbers" lay-verify="only" style="width: 318px;margin-top: 0px;" placeholder="请输入对账单号">
							<input type="hidden" id="id" name="id">
							<span class="xing" style="margin-left: 101%;"></span>
						</td>
					</tr>
                   	<tr style="height: 10px">
                   	</tr>
					<tr>
						<td>
							<label class="layui-form-label">供应商</label></td>
						<td>
							<select class="layui-input" id="sid" name="sid" lay-verify="required" style="width: 318px;margin-top: 0px;" placeholder="请选择供应商" lay-search>
								<option value="">请选择供应商</option>
								<c:forEach items="${customers}" var="customer">
									<option value="${customer.id}">${customer.customer_name}</option>
								</c:forEach>  
							</select>
							<span class="xing" style="margin-left: 101%;"></span>
						</td>
					</tr>
                   	<tr style="height: 10px">
                   	</tr>
					<tr>
						<td>
							<label class="layui-form-label">对账月份</label></td>
						<td>
							<input class="layui-input" id="remark1" name="remark1" lay-verify="required" style="width: 318px;margin-top: 0px;" placeholder="请输入对账月份">
							<span class="xing" style="margin-left: 101%;"></span>
						</td>
					</tr>
                   	<tr style="height: 10px">
                   	</tr>
					<tr>
						<td>
							<label class="layui-form-label">对账时间</label></td>
						<td>
							<div>
								<input class="layui-input" id="startTime" name="startTime" lay-verify="required" style="width: 152px;margin-top: 0px;display:inline;" placeholder="请输入开始时间">
								-
								<input class="layui-input" id="endTime" name="endTime" lay-verify="required" style="width: 152px;margin-top: 0px;display:inline;" placeholder="请输入截止时间">
							</div>
							<span class="xing" style="margin-left: 101%;"></span>
						</td>
					</tr>
                   	<tr style="height: 10px">
                   	</tr>
					<tr>
						<td>
							<label class="layui-form-label">配送税率</label></td>
						<td>
							<input class="layui-input" id="taxRate" name="taxRate" lay-verify="taxRate" style="width: 318px;margin-top: 0px;" placeholder="请输入配送税率">
						</td>
					</tr>
                   	<tr style="height: 10px">
                   	</tr>
					<tr>
						<td>
							<label class="layui-form-label">结算方式</label></td>
						<td>
							<select class="layui-input" name="settlement" id="settlement" lay-verify="required" style="width:318px;margin-left: 0px;margin-top: 0px;" xm-select="select1">
									<option value="2">按固定费用</option>
									<option value="0">按出库数量</option>
									<option value="1">按运输趟数</option>
							</select>
							<span class="xing" style="margin-left: 101%;"></span>
						</td>
					</tr>
                   	<tr style="height: 10px">
                   	</tr>
					<tr>
						<td>
							<label class="layui-form-label">备注</label></td>
						<td>
							<input class="layui-input" id="remark" name="remark" style="width: 318px;margin-top: 0px;" placeholder="请输入备注">
						</td>
					</tr>
					<tr style="height:20px">
					</tr>
				</table>
			</xblock>
			<xblock>
				<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm" style="margin-left:150px; margin-bottom: 10px">立即提交</button>
				&emsp;&emsp;&emsp;&emsp;
				<button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button>
			</xblock>
			</table>
		</form>
    </div>
	<!-- 打印表单框 -->
	<div id="dybdDivID" hidden="hidden">
		<div id="dyDiv" style="width: 100%;overflow-y:scroll;height: 549px">
			<table style="width: 100%;">
				<tr>
					<td align="center">
						<h1>销售对账单</h1>
					</td>
				</tr>
				<tr style="height:3px"></tr>
				<tr>
					<td width="100%" align="center">
						<table width="75%">
							<tr>
								<td width="20%">
									对账单号：<span id="s1"></span>
								</td>
								<td width="20%">
									客户名称：<span id="s2"></span>
								</td>
								<td width="40%">
									期间：<span id="s3"></span>
								</td>
								<td width="20%">
									对账时间：<span id="s4"></span>
								</td>
							</tr>
						</table>
					</td>
				</tr>
				<tr style="height:5px"></tr>
				<tr>
					<td width="100%" align="center">
						<table id="dytable" lay-filter="dytable">
						</table>
					</td>
				</tr>
				<tr>
					<td width="100%" align="center">
						<table width="75%">
							<tr>
								<td align="right">
									对账人：<span id="s5"></span>
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
		</div>
		<xblock>
			<div align="right" style="margin-bottom: 0px;">
				<button type="button" id="dayingTable" class="layui-btn" style="margin-left: 450px;background-color: #57575799;"><i class="layui-icon">&#xe66e;</i>打印</button>
			</div>
		</xblock>
	</div>
	<script type="text/javascript">
		//全局定义一次, 加载formSelects
	    layui.config({
	        base: '../src/' //此处路径请自行处理, 可以使用绝对路径
	    }).extend({
	        formSelects: 'formSelects-v4'
	    });
	
        var table;
		layui.use(['table','layer','upload','form','laydate'], function(){
			table = layui.table;
			var layer = layui.layer;
			var form = layui.form;
			var laydate = layui.laydate;
			
			var formSelects = layui.formSelects;
			
			//执行一个laydate实例
			laydate.render({
				elem: '#remark1', //指定元素
				type: 'month',
				value: new Date(),
				format: 'yyyy-MM', //自动生成的时间格式   
				btns: ['now', 'confirm']
			});
			
			//日期时间范围
	    	var minListDate = "1000-01-01 00:00:00";//最小可选时间，例：1990-02-01
	        var maxListDate = curentTime()+' 23:59:59';//最大可选时间，例：2200-12-31   
	        var maxListDate1 = "3000-12-31 23:59:59";//最大可选时间，例：2200-12-31   
	        var enddate = laydate.render({
	            elem: "#endTime",
	            format: 'yyyy-MM-dd HH:mm:ss',
	            type: 'datetime',
	            min: minListDate,
	            max: maxListDate,
	            done: function (val, date) {
	                if (date && date.year){
	                	//设置结束时间 设置开始时间的最大值为结束时间
	                    begindate.config.max = {
	                        year: date.year,
	                        month: date.month - 1,//必须减1才是正确值
	                        date: date.date,
	                        hours: date.hours,
	                        minutes: date.minutes,
	                        seconds: date.seconds
	                    };
	                }else {
	                	//清除结束值    设置开始时间最大值
	                    var dateInit = new Date(maxListDate.replace(/-/g, "/"));
	                    begindate.config.max = {
	                        year: dateInit.getFullYear(),
	                        month: dateInit.getMonth(),
	                        date: dateInit.getDate(),
	                        hours: dateInit.getHours(),
	                        minutes: dateInit.getMinutes(),
	                        seconds: dateInit.getSeconds()
	                    };
	                }
	            }
	        });
	        var begindate = laydate.render({
	            elem: "#startTime",
	            format: 'yyyy-MM-dd HH:mm:ss',
	            type: 'datetime',
	            min: minListDate,
	            max: maxListDate,
	            done: function (val, date) {
	                if (date && date.year){
	                	//设置开始时间 设置结束时间的最小值为开始时间
	                    enddate.config.min = {
	                        year: date.year,
	                        month: date.month - 1,
	                        date: date.date,
	                        hours: date.hours,
	                        minutes: date.minutes,
	                        seconds: date.seconds
	                    };
	                }else {
	                	//清除开始值 ，设置结束值最小值
	                    var dateInit = new Date(minListDate.replace(/-/g, "/"));
	                    enddate.config.min = {
	                        year: dateInit.getFullYear(),
	                        month: dateInit.getMonth(),
	                        date: dateInit.getDate(),
	                        hours: dateInit.getHours(),
	                        minutes: dateInit.getMinutes(),
	                        seconds: dateInit.getSeconds()
	                    };
	                }
	            }
	        });
	        var enddate1 = laydate.render({
	            elem: "#endTime1",
	            format: 'yyyy-MM-dd HH:mm:ss',
	            type: 'datetime',
	            min: minListDate,
	            max: maxListDate1,
	            done: function (val, date) {
	                if (date && date.year){
	                	//设置结束时间 设置开始时间的最大值为结束时间
	                    begindate1.config.max = {
	                        year: date.year,
	                        month: date.month - 1,//必须减1才是正确值
	                        date: date.date,
	                        hours: date.hours,
	                        minutes: date.minutes,
	                        seconds: date.seconds
	                    };
	                }else {
	                	//清除结束值    设置开始时间最大值
	                    var dateInit = new Date(maxListDate1.replace(/-/g, "/"));
	                    begindate1.config.max = {
	                        year: dateInit.getFullYear(),
	                        month: dateInit.getMonth(),
	                        date: dateInit.getDate(),
	                        hours: dateInit.getHours(),
	                        minutes: dateInit.getMinutes(),
	                        seconds: dateInit.getSeconds()
	                    };
	                }
	            }
	        });
	        var begindate1 = laydate.render({
	            elem: "#startTime1",
	            format: 'yyyy-MM-dd HH:mm:ss',
	            type: 'datetime',
	            min: minListDate,
	            max: maxListDate1,
	            done: function (val, date) {
	                if (date && date.year){
	                	//设置开始时间 设置结束时间的最小值为开始时间
	                    enddate1.config.min = {
	                        year: date.year,
	                        month: date.month - 1,
	                        date: date.date,
	                        hours: date.hours,
	                        minutes: date.minutes,
	                        seconds: date.seconds
	                    };
	                }else {
	                	//清除开始值 ，设置结束值最小值
	                    var dateInit = new Date(minListDate.replace(/-/g, "/"));
	                    enddate1.config.min = {
	                        year: dateInit.getFullYear(),
	                        month: dateInit.getMonth(),
	                        date: dateInit.getDate(),
	                        hours: dateInit.getHours(),
	                        minutes: dateInit.getMinutes(),
	                        seconds: dateInit.getSeconds()
	                    };
	                }
	            }
	        });
			
			var $ = layui.jquery, active = {
				reload:function () {
					var keyword01 = $.trim($("#keyword01").val());
	                var keyword02 = $.trim($("#keyword02").val());
	                var keyword03 = $.trim($("#keyword03").val());
	                var createTime = ""
	                var startTime = $.trim($("#startTime1").val());
					if(startTime != null && startTime != ""){
						createTime = createTime + " and createTime >= '"+startTime+"' ";
					}
					var endTime = $.trim($("#endTime1").val());
					if(endTime != null && endTime != ""){
						createTime = createTime + " and createTime <= '"+endTime+"' ";
					}
					table.reload('tableList',{
						method:'get'
						,where:{
							oddNumbers:keyword01
	                        ,sid:keyword02
	                        ,createTime:createTime
	                        ,isReconciliation:keyword03
						}
						,page: {
		                    curr: 1//重新从第 1 页开始
		                }
					});
				}
			}
			$('.layui-btn').on('click', function(){
				var type = $(this).data('type');
				active[type] ? active[type].call(this) : '';
			});
			var url = '${pageContext.request.contextPath }/saleBill/list.do'
			table.render({
				elem: '#tableList'
				,url:url
				,toolbar: '#toolbar'
				,title: 'machineList'
				,limits:[10,20,30]
                //,defaultToolbar:['filter', 'print']
				,request: {   //如果无需自定义请求参数，可不加该参数
	                pageName: 'page' //页码的参数名称，默认：page
	                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
	            }
	            ,response: {   //如果无需自定义数据响应名称，可不加该参数
	                countName: 'total' //规定数据总数的字段名称，默认：count
	                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
	            }
				,cols: [
		                [{
		                    type: 'checkbox',
		                    fixed: 'left'
		                }, {
		                	field:'id',
		                	title:'序号', 
		                	sort: true,
		                	width: 60,
		                	type:'numbers',
		                	align:'center'
		                }, {
		                    field: 'id',
		                    title: 'id',
		                    hide:true //是否初始隐藏列，默认：false。layui 2.4.0 新增
		                } , {
		                    field: 'oddNumbers',
		                    title: '对账单号',
		                    align:'center',
		                }, {
		                    field: 'sid',
		                    title: '供应商',
		                    align:'center',
	                    	templet: function(d){
		                    	var value = "";
            	    			if(d.customer != null){
            	    				value = d.customer.customer_name
            	    			}
            	    			return value;
            	    		},
		                }, {
		                    field: 'remark1',
		                    title: '对账月份',
		                    align:'center'
		                }, {
		                    field: 'startTime',
		                    title: '对账开始',
		                    align:'center'
		                }, {
		                    field: 'endTime',
		                    title: '对账截止',
		                    align:'center'
		                }, {
		                    field: 'money',
		                    title: '对账金额',
		                    align:'center'
		                }, {
		                    field: 'taxRate',
		                    title: '配送税率',
		                    align:'center'
		                }, {
		                    field: 'smoney',
		                    title: '价税合计',
		                    align:'center',
	                    	/* templet: function(d){
		                    	var value = 0;
            	    			if(d.money != null){
            	    				value = FloatMul((parseFloat(d.taxRate)+1),d.money)//(parseFloat(d.taxRate)+1) * parseFloat(d.money) 
            	    			}
            	    			return value;
            	    		}, */  
		                }, {
		                    field: 'settlement',
		                    title: '结算方式',
		                    align:'center',
	                    	templet: function(d){
	                    		var settlements = d.settlement.split(",");
		                    	var value = "";
	                    		for (var i = 0; i < settlements.length; i++) {
	            	    			if(settlements[i] == 0){
	            	    				value = value + "按出库数量"+","
	            	    			}else if(settlements[i] == 1){
	            	    				value = value + "按运输趟数"+","
	            	    			}else if(settlements[i] == 2){
	            	    				value = value + "按固定费用"+","
	            	    			}
								}
            	    			return value;
            	    		},
		                }, {
		                    field: 'createMan',
		                    title: '对账人',
		                    align:'center',
		                }, {
		                    field: 'createTime',
		                    title: '对账时间',
		                    align:'center',
		                }, {
		                    field: 'isReconciliation',
		                    title: '是否对账',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.isReconciliation == 0){
            	    				value = "否"
            	    			}else{
            	    				value = "是"
            	    			}
            	    			return value;
            	    		},
		                }, {
		                    field: 'remark',
		                    title: '备注',
		                    align:'center'
		                /* }, {
		                    fixed: 'right',
		                    title:'操作',
		                    toolbar: '#rowToolbar',
		                    align:'center',
		                    unresize: true,
		                    width: 150 */ 
		                }
		                ]
		               ]
				,page: true
				,done : function(){
					$('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
	            }
			});
			
			table.render({
				elem: '#tableListDetails'
				,url:'${pageContext.request.contextPath }/saleBillDetails/list.do'
				,where:{
					bid:-1
				}
				,toolbar: '#toolbar'
				,title: 'machineList'
				,limits:[10,20,30]
                //,defaultToolbar:['filter', 'print']
				,request: {   //如果无需自定义请求参数，可不加该参数
	                pageName: 'page' //页码的参数名称，默认：page
	                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
	            }
	            ,response: {   //如果无需自定义数据响应名称，可不加该参数
	                countName: 'total' //规定数据总数的字段名称，默认：count
	                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
	            }
	            ,totalRow: true
				,cols: [
		                [{
		                    type: 'checkbox',
		                    fixed: 'left'
		                }, { 
		                	field:'bdid',
		                	title:'序号', 
		                	sort: true,
		                	width: 60,
		                	type:'numbers',
		                	align:'center'
		                }, {
		                    field: 'bdid',
		                    title: 'id',
		                    hide:true //是否初始隐藏列，默认：false。layui 2.4.0 新增
		                } , {
		                    field: 'kid',
		                    title: '科目',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.saleExpenseAccount != null){
            	    				value = d.saleExpenseAccount.ename
            	    			}
            	    			return value;
            	    		},
		                } , {
		                    field: 'mid',
		                    title: '物料名称',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.materiel != null){
            	    				value = d.materiel.materiel_name
            	    			}
            	    			return value;
            	    		},
            	    		totalRowText:"合计"
		                } , {
		                    field: 'mid',
		                    title: 'SAP/QAD',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.materiel != null){
            	    				value = d.materiel.materiel_num
            	    			}
            	    			return value;
            	    		},
		                }, {
		                    field: 'bdnum',
		                    title: '数量',
		                    align:'center',
		                    edit:true,
		                    style:"color: blue;"
		                }, {
		                    field: 'bddzMoney',
		                    title: '单价',
		                    align:'center',
		                }, {
		                    field: 'money',
		                    title: '对账金额',
		                    align:'center',
	                    	templet: function(d){
		                    	var value = 0;
            	    			if(d.bdnum != null){
            	    				value = FloatMul(d.bddzMoney,d.bdnum)//parseFloat(d.bddzMoney) * parseInt(d.bdnum) 
            	    			}
            	    			return value;
            	    		},  
            	    		totalRow: true
						}, {
		                    field: 'bdremark',
		                    title: '税率',
		                    align:'center',
		                }, {
		                    field: '',
		                    title: '价税合计',
		                    align:'center',
	                    	templet: function(d){
		                    	var value = 0;
		                    	if(d.bdnum != null){
			                    	var money = FloatMul(d.bddzMoney,d.bdnum)//parseFloat(d.bddzMoney) * parseInt(d.bdnum) 
            	    				value = FloatMul((parseFloat(d.bdremark)+1),money)//(parseFloat(d.bdremark)+1) * money
            	    			} 
            	    			return value;
            	    		}, 
            	    		totalRow: true
		                /* }                                                                                                                                                                                                                                                 , {
		                    field: 'bdisReconciliation',
		                    title: '是否对账',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.bdisReconciliation == 0){
            	    				value = "否"
            	    			}else{
            	    				value = "是"
            	    			}
            	    			return value;
            	    		}, */
		                }
		                ]
		               ]
				,page: true
				,done : function(res, curr, count){
					$('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                    
                    var sum=0;
                    var ssum=0;
					var data = res.rows;
					for (var i = 0; i < data.length; i++) {
						var a = FloatMul(data[i].bddzMoney,data[i].bdnum)//parseFloat(data[i].bddzMoney) * parseInt(data[i].bdnum)
                		sum=FloatAdd(sum,a)//sum+a;
						var sa = FloatMul((parseFloat(data[i].bdremark)+1),a)//(parseFloat(data[i].bdremark)+1) * a
	               		ssum=FloatAdd(ssum,sa)//ssum+sa;
					} 
					//  ----- 替换原来的数据
					$("[lay-id='tableListDetails'] .layui-table-total div:eq(8)").html(sum); 
					$("[lay-id='tableListDetails'] .layui-table-total div:eq(10)").html(ssum);
	            }
			});
        	
			/* 打印单据 */
	        table.render({
	            elem: '#dytable'
	            ,title: '明细表'
	            ,totalRow: true
            	,cols: [
		                [{
		                	field:'bdid',
		                	title:'序号', 
		                	sort: true,
		                	width: 60,
		                	type:'numbers',
		                	align:'center'
		                } , {
		                    field: 'kid',
		                    title: '科目',
		                    align:'center',
            	    		width: 100,
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.saleExpenseAccount != null){
            	    				value = d.saleExpenseAccount.ename
            	    			}
            	    			return value;
            	    		},
		                } , {
		                    field: 'mid',
		                    title: '物料名称',
		                    align:'center',
		                    width: 300,
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.materiel != null){
            	    				value = d.materiel.materiel_name
            	    			}
            	    			return value;
            	    		},
            	    		totalRowText:"合计"
		                } , {
		                    field: 'mid',
		                    title: 'SAP/QAD',
		                    align:'center',
		                    width: 200,
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.materiel != null){
            	    				value = d.materiel.materiel_num
            	    			}
            	    			return value;
            	    		},
		                }, {
		                    field: 'bdnum',
		                    title: '数量',
		                    align:'center',
		                    width: 100,
		                }, {
		                    field: 'bddzMoney',
		                    title: '单价',
		                    align:'center',
		                    width: 150,
		                }, {
		                    field: '',
		                    title: '对账金额',
		                    align:'center',
		                    width: 200,
	                    	templet: function(d){
		                    	var value = 0;
            	    			if(d.bdnum != null){
            	    				value = FloatMul(d.bddzMoney,d.bdnum)//parseFloat(d.bddzMoney) * parseInt(d.bdnum) 
            	    			}
            	    			return value;
            	    		},  
            	    		totalRow: true
            	    		
		                }, {
		                    field: 'bdremark',
		                    title: '税率',
		                    align:'center',
		                    width: 100,
		                }, {
		                    field: '',
		                    title: '价税合计',
		                    align:'center',
		                    width: 200,
	                    	templet: function(d){
		                    	var value = 0;
		                    	if(d.bdnum != null){
			                    	var money = FloatMul(d.bddzMoney,d.bdnum)//parseFloat(d.bddzMoney) * parseInt(d.bdnum) 
            	    				value = FloatMul((parseFloat(d.bdremark)+1),money)//(parseFloat(d.bdremark)+1) * money
            	    			} 
            	    			return value;
            	    		}, 
             	    		totalRow: true
		                /* }                                                                                                                                                                                                                                                 , {
		                    field: 'bdisReconciliation',
		                    title: '是否对账',
		                    align:'center',
		                    templet: function(d){
		                    	var value = "";
            	    			if(d.bdisReconciliation == 0){
            	    				value = "否"
            	    			}else{
            	    				value = "是"
            	    			}
            	    			return value;
            	    		}, */
		                }
		                ]
		               ]
				,page: false
				,done : function(res, curr, count){
					$('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                    var sum=0;
					var ssum=0;
					var data = res.data;
					for (var i = 0; i < data.length; i++) {
						var a = FloatMul(data[i].bddzMoney,data[i].bdnum)//parseFloat(data[i].bddzMoney) * parseInt(data[i].bdnum)
                		sum=FloatAdd(sum,a)//sum+a;
                		var sa = FloatMul((parseFloat(data[i].bdremark)+1),a)//(parseFloat(data[i].bdremark)+1) * a
                		ssum=FloatAdd(ssum,sa)//ssum+sa;
					} 
                	//alert(sum)
					/* console.log(res.data);
					//选中我们要操作的合计列
					var a = $(".layui-table-total div:eq(8)").html();
					alert(a)*/
					//  ----- 替换原来的数据
					$(".layui-table-total div:eq(6)").html(sum); 
					$("[lay-id='dytable'] .layui-table-total div:eq(8)").html(ssum);
	            }
	        });
			
	        table.on('row(tableList)', function(obj){
	        	var data = obj.data;
	        	document.getElementById("detailsDiv").style.display="block";
	        	 if(data.isReconciliation == 1){
		        	table.reload('tableListDetails',{
						method:'get'
						,where:{
	                        bid:data.id
						}
						,page: {
		                    curr: 1//重新从第 1 页开始
		                }
						,done: function (res, curr, count) {
							$('td[data-field="bdnum"]').data('edit', false) 
							$('td[data-field="bdnum"]').attr({"style":"color: #666;"}) 
							$('th').css({
		                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
		                    })
		                    var sum=0;
		                    var ssum=0;
							var data = res.rows;
							for (var i = 0; i < data.length; i++) {
								var a = FloatMul(data[i].bddzMoney,data[i].bdnum)//parseFloat(data[i].bddzMoney) * parseInt(data[i].bdnum)
		                		sum=FloatAdd(sum,a)//sum+a;
								var sa = FloatMul((parseFloat(data[i].bdremark)+1),a)//(parseFloat(data[i].bdremark)+1) * a
		                		ssum=FloatAdd(ssum,sa)//ssum+sa;
							} 
							//  ----- 替换原来的数据
							$("[lay-id='tableListDetails'] .layui-table-total div:eq(8)").html(sum); 
							$("[lay-id='tableListDetails'] .layui-table-total div:eq(10)").html(ssum);
						}
					});
	        	}else{
		        	table.reload('tableListDetails',{
						method:'get'
						,where:{
	                        bid:data.id
						}
						,page: {
		                    curr: 1//重新从第 1 页开始
		                }
						,done: function (res, curr, count) {
							$("td[data-field='bdnum']").data('edit', true) 
							$('th').css({
		                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
		                    })
		                    var sum=0;
		                    var ssum=0;
							var data = res.rows;
							for (var i = 0; i < data.length; i++) {
								var a = FloatMul(data[i].bddzMoney,data[i].bdnum)//parseFloat(data[i].bddzMoney) * parseInt(data[i].bdnum)
		                		sum=FloatAdd(sum,a)//sum+a;
								var sa = FloatMul((parseFloat(data[i].bdremark)+1),a)//(parseFloat(data[i].bdremark)+1) * a
		                		ssum=FloatAdd(ssum,sa)//ssum+sa;
							} 
							//  ----- 替换原来的数据
							$("[lay-id='tableListDetails'] .layui-table-total div:eq(8)").html(sum); 
							$("[lay-id='tableListDetails'] .layui-table-total div:eq(10)").html(ssum);
						}
					});
	        	} 
	        });
	      	
	        //点击行checkbox选中
    	    $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
    	        var index = $(this).attr('data-index');
    	        var tableBox = $(this).parents('.layui-table-box');
    	        //存在固定列
    	        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
    	            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
    	        } else {
    	            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
    	        }
    	        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
    	        if (checkCell.length>0) {
    	            checkCell.click();
    	        }
    	    });
    	    $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
    	        e.stopPropagation();
    	    });
	        table.on('checkbox(tableList)', function(obj){
	        	if(obj.checked == true && obj.type == 'all'){
	                //点击全选
	                $('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click');
	            }else if(obj.checked == false && obj.type == 'all'){
	                //点击全不选
	                $('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
	            }else if(obj.checked == true && obj.type == 'one'){
	                //点击单行
	                if(obj.checked == true){
	                    obj.tr.addClass('layui-table-click');
	                }else{
	                    obj.tr.removeClass('layui-table-click');
	                }
	            }else if(obj.checked == false && obj.type == 'one'){
	                //点击全选之后点击单行
	                if(obj.tr.hasClass('layui-table-click')){
	                    obj.tr.removeClass('layui-table-click');
	                }
	            }
	        });
	      //"详细"的行内编辑事件
            table.on('edit(tableListDetails)', function(obj){
                var fieldValue = obj.value, 	//得到修改后的值
                    rowData = obj.data, 		//得到所在行所有键值
                    fieldName = obj.field; 		//得到字段
               	var firstValue = $(this).prev().text(); 	//得到修改前的值
               	var patrn = /^[0-9]*$/;
               	if(!patrn.test(fieldValue)){
               		toastr.warning("只能是数字！");
               		table.reload('tableListDetails',{});
               		//$(this)[0].value = $(this).prev().text();
               	} else {
	               	//保存修改出库单详细表的值    
                    layui.use('jquery',function(){
                        var $ = layui.$;
                        $.ajax({
                            type: "post",
                            url: "${pageContext.request.contextPath}/saleBillDetails/update.do",
                            data: {bdid:rowData.bdid, bdnum:fieldValue },
                            success: function(count){
                                if(count > 0){
                                    toastr.success("修改成功！");
                                    table.reload('tableListDetails',{});
                                    table.reload('tableList',{});
                                }else{
                                    toastr.warning("修改失败！");
                                    table.reload('tableListDetails',{}); 
                                }
                            }
                        });
                    });
               	}
            });
			//监听行工具事件
			table.on('tool(tableList)', function(obj){
				var data = obj.data;
				//alert(data.id)
				var idArr = new Array();
				if(obj.event === 'edit'){
					layer.open({
					  type: 1 							//Page层类型
					  ,area: ['500px', ''] 	//宽  高
					  ,title: '编辑'
					  ,shade: 0.6 						//遮罩透明度
					  ,maxmin: true 					//允许全屏最小化
					  ,anim: 1 							//0-6的动画形式，-1不开启
					  ,content: $('#addDivID')
	                  ,end: function () {
	                      var formDiv = document.getElementById('addDivID');
	                      formDiv.style.display = '';
	                  }
	                  ,success: function(){
	                      $("#id").val(data.id)
	                      $("#oddNumbers").val(data.oddNumbers)
	                      $("#sid").val(data.sid)
	                      $("#startTime").val(data.startTime)
	                      $("#endTime").val(data.endTime)
	                      $("#taxRate").val(data.taxRate)
	                      $("#settlement").val(data.settlement)
	                      $("#remark").val(data.remark)
	                      form.render();
	                    }
					});
				}
			});
			/**
			 * 通用表单提交(AJAX方式)(新增)
			 */
			form.on('submit(addForm)', function (data) {
				var index = layer.load(1, {
	        	    shade: [0.1,'#000'] //0.1透明度的背景
	        	});
				
				var formData = $("#addFormID").serialize();
				var title = "新增";
				var url = '${pageContext.request.contextPath}/saleBill/insert.do';
				var eid = $.trim($("#eid").val());
				if(eid != "" && eid != null && eid != 'undefined'){
					var url = '${pageContext.request.contextPath}/saleBill/update.do';
					title = "修改";
				}
				$.ajax({
					url : url,
					data: formData,
					cache : false,
					type : "post",
					success: function (data) {
	                    if (data >= 1) {
	                        toastr.success(title+'成功');
	                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	                            window.location.reload();
	                            $("#reset").click();
	                        },1000);
	                    } else {
	                        toastr.error(title+'失败，该费用科目名称已存在，不能重复');
	                    }
	                },
				})
				layer.close(index);
				return false;
			});

			

			/**
			 * 新增表单校验
			 */
			form.verify({
				//value：表单的值、item：表单的DOM对象
	            required: function(value, item){
	            	value = $.trim(value)
	            	if(value == '' || value == null){
	                    return '不能为空';
	                }
	            },
				//value：表单的值、item：表单的DOM对象
	            /* taxRate: function(value, item){
	            	value = $.trim(value)
	            	var re = /^(\d|[1-9]\d|100)(\.\d{1,4})?$/;
	            	if(value == '' || value == null){
	                    return '不能为空';
	                }else if(value != '' && value != null && !re.test(value)){
	                    return '请输入大于0的小数（最多4位小数）';
	                }
	            }, */
	            taxRate: function(value, item){
 	            	value = $.trim(value)
	            	var arr = formSelects.value('select1', 'val');        // ["2","4"]
 	            	var re = /^(\d|[1-9]\d|100)(\.\d{1,4})?$/;
	            	//配送费低于状态
	            	var s = '0';
	            	if(arr.indexOf(s) != -1 && (value == '' || value == null)){
	                    return '结算方式有选择按出库数量,配送税率不能为空';
	            	}else if(arr.indexOf(s) == -1 && value != '' && value != null){
	            		$("#taxRate").val("")
	                    return '结算方式没有选择按出库数量自动清空配送税率';
 	                }else if(value != '' && value != null && !re.test(value)){
 	                    return '请输入大于0的小数（最多4位小数）';
 	                }
	            },
				//value：表单的值、item：表单的DOM对象
	            only: function(value, item){
	            	value = $.trim(value)
	            	if(value == '' || value == null){
	                    return '不能为空';
	                }else{
	                    var flg = false;
	                    $.ajax({
	                        type:'post',
	                        data:'oddNumbers='+value,
	                        url:'${pageContext.request.contextPath}/saleBill/queryAllByMution.do',
	                        dataType: 'JSON',
	                        async: false,
	                        success:function (data) {
	                            if(data.length == 0){
	                                flg  = true;
	                            }else if(data.length == 1){
	                                var ma = $.trim($("#id").val());
	                                if (ma == data[0].id) {
	                                    flg  = true;
	                                }else{
	                                    flg = false;
	                                }
	                            }else{
	                                flg = false;
	                            }
	
	                        }
	                    });
	                    if(!flg){
	                        return '科目名称不能重复';
	                    }
	                }
	            }
			});

			
			//增加
            $("#add").click(function(){
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['500px', ''] 	//宽  高
                    ,title: '新增'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content: $('#addDivID')
                    ,end: function () {
                        var formDiv = document.getElementById('addDivID');
                        formDiv.style.display = '';
                    }
                    ,success: function(){
                    	 $("#id").val("")
	                     $("#oddNumbers").val(curentTimeNumber())
	                     $("#sid").val("")
	                     $("#startTime").val(curentTimeshangyue()+" 00:00:00")
	                     $("#endTime").val(curentTime()+" 00:00:00")
	                     $("#taxRate").val("")
	                     $("#settlement").val("")
	                     $("#remark").val("")
                        form.render();
                    }
                });
			});

			

          	//批量删除
			$("#dels").click(function(){
				var checkStatus = table.checkStatus('tableList')
	      		var data = checkStatus.data;
	            var idArr = new Array();
	            if(data.length==0){
	                toastr.warning("请至少选择一条记录！");
	            }else{
	            	var names = "";
	                var ids = "";
	                for(var i=0;i<data.length;i++){
	                    if(data[i].isReconciliation == 1){
	                    	names = names+data[i].oddNumbers+","
	                    }else{
	                    	if(ids == ""){
		                        ids += data[i].id;
		                    }else{
			                        ids += "," + data[i].id;
		                    }
	                    }
	                }
	                if(names != ""){
	                	names =  "已对账："+names+"还有其他可删除，"
	                }
	                if(ids == ""){
	                	toastr.warning("请至少选择一条记录！！");
	                }else{
		                layer.confirm(names+'确定删除吗？', function(index){
		                    $.ajax({
		                        type:'post',
		                        url:'${pageContext.request.contextPath }/saleBill/delete.do',
		                        data:{"ids":ids},
		                        success:function(data){
		                            if(data>0){
		                                toastr.success("删除成功！");
		                                setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
		                                    //关闭模态框
		                                    // 父页面刷新
		                                    window.location.reload();
		                                },2000);
		                            }else{
		                                toastr.warning("删除失败！");
		                            }
		                        }
	
		                    })
		                    layer.closeAll();
		                });
	                }
	            }
			});
          	//批量启用
			$("#reconciliation").click(function(){
				var checkStatus = table.checkStatus('tableList')
	      		var data = checkStatus.data;
	            var idArr = new Array();
	            if(data.length==0){
	                toastr.warning("请至少选择一条记录！");
	            }else{
	                var names = "";
	                var ids = "";
	                for(var i=0;i<data.length;i++){
	                    if(data[i].isReconciliation == 1){
	                    	names = names+data[i].oddNumbers+","
	                    }else{
	                    	if(ids == ""){
		                        ids += data[i].id;
		                    }else{
			                        ids += "," + data[i].id;
		                    }
	                    }
	                }
	                if(names != ""){
	                	names =  "已对账："+names+"还有其他可对账，"
	                }
	                if(ids == ""){
	                	toastr.warning("所选数据已对账！！");
	                }else{
		                layer.confirm(names+'确定对账吗？', function(index){
		                    $.ajax({
		                        type:'post',
		                        url:'${pageContext.request.contextPath }/saleBill/updateIsReconciliationByIds.do',
		                        data:{"ids":ids,"isReconciliation":1},
		                        success:function(data){
		                            if(data>0){
		                                toastr.success("对账成功！");
		                                setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
		                                    //关闭模态框
		                                    // 父页面刷新
		                                    window.location.reload();
		                                },2000);
		                            }else{
		                                toastr.warning("对账失败！");
		                            }
		                        }
	
		                    })
		                    layer.closeAll();
		                });
	                }
	            }
			});
          	//批量禁用
			$("#printing").click(function(){
				var checkStatus = table.checkStatus('tableList')
	      		var datas = checkStatus.data;
	            var idArr = new Array();
	            if(datas.length!=1){
	                toastr.warning("请选择一条记录！");
	            }else{
	            	var data = datas[0]
		            layer.open({
		                type: 1 					//Page层类型
		                ,area: ['1450px', '650px'] 			//宽  高
		                ,title: '打印表单'
		                ,shade: 0.6 				//遮罩透明度
		                ,maxmin: true 				//允许全屏最小化
		                ,anim: 1 					//0-6的动画形式，-1不开启
		                ,content: $('#dybdDivID')
		                ,end: function () {
		                    var formDiv = document.getElementById('dybdDivID');
		                    formDiv.style.display = '';
		                }
		                ,success: function(){
		                	//alert(data.sendPhone + "== "+ data.sendAdress);
	                        $("#s1").html(data.oddNumbers);
	                        $("#s2").html(data.customer.customer_name);
	                        $("#s3").html(data.startTime+"-"+data.endTime);
	                        $("#s4").html(data.createTime);
	                        $("#s5").html(data.createMan);
	                        
	                        var newData = new Array();
	                        $.ajax({
	                            type:'post',
	                            data:'bid='+data.id,
	                            url:'${pageContext.request.contextPath}/saleBillDetails/queryAllByMution.do',
	                            dataType: 'JSON',
	                            async: false,
	                            success:function (data) {
	                                console.log(data);
	                            	newData = data;
	                            }
	                        });
	                        table.reload('dytable',{
	                            data : newData
	                            ,limit:newData.length
	                        });
		                }
		            });
	            }
			});
			$("#dayingTable").click(function(){
				//var innerHTML = document.getElementById("dyDiv").innerHTML;
	        	//printpage(innerHTML)
			    var obj =document.getElementById('dyDiv')
				var css='<style>'
	                //+"#dyTable td{border:1px solid #00000080;}"
	                +'[lay-id="dytable"] table{border:1px solid #F00;border-collapse:collapse;}'
	                +'[lay-id="dytable"] table td{border:1px solid #222;}'
	                +'[lay-id="dytable"] table th{border:1px solid #222;font-size: 20px;}'
	                +'[lay-id="dytable"] table th span{color: black;}'
	                +'</style>'; 
				var newWindow=window.open("打印窗口","_blank");//打印窗口要换成页面的url
				var docStr =  css+ obj.innerHTML;
			    newWindow.document.write(docStr);
			    newWindow.document.close();
			    setTimeout(function () {
				    newWindow.print();
				    newWindow.close();
			    }, 100);
			});
			  
		});
		
		//获取当前时间
	   	function curentTimeNumber() {
	   		var now=new Date();
	   		var year = now.getFullYear();       //年
	   	    var month = now.getMonth() + 1;     //月
	   	    var day = now.getDate();            //日
	   	 	var hours = now.getHours(); //获取当前小时数(0-23)
		   	var minutes = now.getMinutes(); //获取当前分钟数(0-59)
		   	var seconds = now.getSeconds(); //获取当前秒数(0-59)
	   	    //var mill=now.getMilliseconds();
	   	    var time=year+""+add0(month)+""+add0(day)+""+add0(hours)+""+add0(minutes)+""+add0(seconds);
	   		return time;
	   	}
	    //获取当前时间
	   	function curentTimeshangyue() {
	   		var now=new Date();
	   		var year = now.getFullYear();       //年
	   	    var month = now.getMonth()+1;     //月
	   	    var day = now.getDate();            //日
	   	    var time=year+"-"+add0(month)+"-"+add0(day);
	   	 	time = getPreMonth(time)
	   		return time;
	   	}
	    //获取当前时间
	   	function curentTime() {
	   		var now=new Date();
	   		var year = now.getFullYear();       //年
	   	    var month = now.getMonth() + 1;     //月
	   	    var day = now.getDate();            //日
	   	    var time=year+"-"+add0(month)+"-"+add0(day);
	   		return time;
	   	}
	   	function add0(m){return m<10?'0'+m:m }
		toastrStyle()
		/*获取上个月*/
		function getPreMonth(date) {
			var arr = date.split('-');
			var year = arr[0]; //获取当前日期的年份
			var month = arr[1]; //获取当前日期的月份
			var day = arr[2]; //获取当前日期的日
			var days = new Date(year, month, 0);
			days = days.getDate(); //获取当前日期中月的天数
			var year2 = year;
			var month2 = parseInt(month) - 1;
			if (month2 == 0) {
				year2 = parseInt(year2) - 1;
				month2 = 12;
			}
			var day2 = day;
			var days2 = new Date(year2, month2, 0);
			days2 = days2.getDate();
			if (day2 > days2) {
				day2 = days2;
			}
			if (month2 < 10) {
				month2 = '0' + month2;
			}
			var t2 = year2 + '-' + month2 + '-' + day2;
			return t2;
		}
		/*获取下个月*/
		function getNextMonth(date) {
			var arr = date.split('-');
			var year = arr[0]; //获取当前日期的年份
			var month = arr[1]; //获取当前日期的月份
			var day = arr[2]; //获取当前日期的日
			var days = new Date(year, month, 0);
			days = days.getDate(); //获取当前日期中的月的天数
			var year2 = year;
			var month2 = parseInt(month) + 1;
			if (month2 == 13) {
				year2 = parseInt(year2) + 1;
				month2 = 1;
			}
			var day2 = day;
			var days2 = new Date(year2, month2, 0);
			days2 = days2.getDate();
			if (day2 > days2) {
				day2 = days2;
			}
			if (month2 < 10) {
				month2 = '0' + month2;
			}
			var t2 = year2 + '-' + month2 + '-' + day2;
			return t2;
		}
		//浮点数加法运算
        function FloatAdd(arg1,arg2){
            var r1,r2,m;
            try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
            try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
            m=Math.pow(10,Math.max(r1,r2));
            return (arg1*m+arg2*m)/m;
        }
      //浮点数减法运算
        function FloatSub(arg1,arg2){
            var r1,r2,m,n;
            try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
            try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
            m=Math.pow(10,Math.max(r1,r2));
            //动态控制精度长度
            n=(r1=r2)?r1:r2;
            return ((arg1*m-arg2*m)/m).toFixed(n);
        }
      	//浮点数乘法运算
        function FloatMul(arg1,arg2)
        {
            var m=0,s1=arg1.toString(),s2=arg2.toString();
            try{m+=s1.split(".")[1].length}catch(e){}
            try{m+=s2.split(".")[1].length}catch(e){}
            return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
        }
      	//浮点数除法运算
        function FloatDiv(arg1,arg2){
            var t1=0,t2=0,r1,r2;
            try{t1=arg1.toString().split(".")[1].length}catch(e){}
            try{t2=arg2.toString().split(".")[1].length}catch(e){}
            with(Math){
                r1=Number(arg1.toString().replace(".",""));
                r2=Number(arg2.toString().replace(".",""));
                return (r1/r2)*pow(10,t2-t1);
            }
        }
	</script>
	<script charset="utf-8" src="${pageContext.request.contextPath }/assets/formSelects/formSelects-v4.min.js"></script>
</body>
</html>